package com.overlord.im.commons.message.protobuf;

import com.overlord.im.commons.constant.AckType;
import com.overlord.im.commons.constant.MsgType;
import com.overlord.im.commons.constant.OverlordImConstants;
import com.overlord.im.commons.constant.SystemType;
import com.overlord.im.commons.message.MessageProtocolConverter;
import com.overlord.im.commons.message.OverlordImMessage;
import io.netty.buffer.ByteBuf;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Optional;

/**
 * @ClassName ProtobufMessageConverter
 * @Author wuwei
 * @Description NONE
 * @Date 2020/5/29 13:30
 **/
public class ProtobufMessageConverter implements MessageProtocolConverter {

    @Override
    public void encode(ByteBuf out, OverlordImMessage message) throws IOException {
        ProtobufMessage.Message.Builder builder =
                ProtobufMessage.Message.newBuilder().setFrom(message.getFrom()).setTo(message.getTo())
                        .setMessageId(Optional.ofNullable(message.getClientMessageId()).orElse(OverlordImConstants.NONE_MESSAGE_ID));
        if (StringUtils.isNotBlank(message.getContent())) {
            String content = message.getContent();
            builder.setContent(content);
        }
        ProtobufMessage.Message build = builder.build();
        byte[] bytes = build.toByteArray();
        int length = bytes.length;
        length = (length << 8) >>> 8;
        out.writeMedium(length);
        out.writeBytes(bytes);
    }

    @Override
    public OverlordImMessage decode(ByteBuf in, int version, int type, int ackTypeCode,
                                    byte systemTypeCode, Long sequenceId) throws IOException {
        MsgType msgType = MsgType.fromCode(type);
        AckType ackType = AckType.fromCode(ackTypeCode);
        SystemType systemType = SystemType.fromCode(systemTypeCode);
        ProtobufMessage.Message message = ProtobufMessage.Message.parseFrom(in.array());
        OverlordImMessage.OverlordImMessageBuilder content =
                OverlordImMessage.builder().msgType(msgType).version(version).token(message.getToken())
                        .clientMessageId(message.getMessageId()).from(message.getFrom()).to(message.getTo()).sequenceId(sequenceId)
                        .ackType(ackType).systemType(systemType).content(message.getContent());
        return content.build();
    }

}
